<script setup lang="ts">
import type { Ref } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { Search, Refresh } from '@element-plus/icons-vue';

import SubViewContainer from '@core/components/subLayout/SubViewContainer.vue';
import TableWithPagination from '@core/components/TableWithPagination.vue';
import * as Enums from '@firewall/engine/Enums';
import UsageGuideStepsVue from '@firewall/components/UsageGuideSteps.vue';
import Firewall, { FirewallInstance } from '@firewall/engine/Firewall';
import OrderHelper from '@firewall/utils/OrderHelper';

const { t } = useI18n({ inheritLocale: true, useScope: 'local' });
const router = useRouter();
const isTableLoading = ref(true);
const QuotaState = {
  All: 'all',
  Normal: 'normal',
  Overdue: 'overdue',
  Unsubscribe: 'unsubscribe',
};
const SearchType = {
  FirewallName: 'firewallName',
  VpcName: 'vpcName',
};
const filters = reactive({
  quotaState: QuotaState.All,
  searchType: SearchType.FirewallName,
  searchKeyword: '',
});
const firewalls: Ref<Array<FirewallInstance>> = ref([]);
const refreshTable = async () => {
  isTableLoading.value = true;
  const response = await Firewall.fetchList({
    firewallName: filters.searchType === SearchType.FirewallName ? filters.searchKeyword : undefined,
    firewallState: filters.quotaState === QuotaState.All ? undefined : filters.quotaState,
    vpcIds: filters.searchType === SearchType.VpcName ? [filters.searchKeyword] : undefined,
  });
  firewalls.value = response.list || [];
  isTableLoading.value = false;
};

onMounted(async () => {
  await refreshTable();
});

const onTableRefresh = async () => {
  await refreshTable();
};

const isFirewallSelectable = (row: FirewallInstance) => {
  if (row.firewallState === 'unsubscribe') return false;
  return true;
};
let selectedVpcIds: Array<string> = [];
const onTableSelectionChange = (firewalls: Array<FirewallInstance>) => {
  selectedVpcIds = firewalls.map((item) => item.vpcId);
};
const onClickBatchRenew = () => {
  if (selectedVpcIds.length === 0) return ElMessage.warning(t('noProductCheckedMessage'));
  router.push({
    name: 'configCenter.quota.renew',
    query: { vpcIds: selectedVpcIds },
  });
};
const onClickRenew = (row: FirewallInstance) => {
  selectedVpcIds = [row.vpcId];
  router.push({
    name: 'configCenter.quota.renew',
    query: { vpcIds: selectedVpcIds },
  });
};
const onClickChange = (row: FirewallInstance) => {
  router.push({
    name: 'configCenter.quota.change',
    query: { vpcId: row.vpcId },
  });
};
const onClickCancel = (row: FirewallInstance) => {
  router.push({
    name: 'configCenter.quota.cancel',
    query: { vpcId: row.vpcId },
  });
};
</script>

<template>
  <SubViewContainer>
    <template #header-suffix>
      <RouterLink :to="{ name: 'configCenter.quota.purchase' }">
        <ElButton type="primary">{{t('toPurchase')}}</ElButton>
      </RouterLink>
    </template>
    <UsageGuideStepsVue class="guide-steps" />
    <ElCard v-loading="isTableLoading">
      <div class="table-controller">
        <ElButton @click="onClickBatchRenew">{{t('batchRenew')}}</ElButton>
        <div class="filters">
          <div class="quota-state">
            <span class="label">{{t('quotaState')}}</span>
            <ElSelect v-model="filters.quotaState">
              <ElOption
                v-for="state in QuotaState"
                :key="state"
                :label="t(`quotaStates.${state}`)"
                :value="state"
              />
            </ElSelect>
          </div>
          <ElInput
            v-model="filters.searchKeyword"
            class="search-input"
            :placeholder="t('inputToSearchPlease')"
            @keyup.enter="onTableRefresh"
          >
            <template #prepend>
              <ElSelect v-model="filters.searchType" >
                <ElOption
                  v-for="item in SearchType"
                  :key="item"
                  :label="t(`searchType.${item}`)"
                  :value="item"
                />
              </ElSelect>
            </template>
            <template #append>
              <ElButton :icon="Search" @click="onTableRefresh" />
            </template>
          </ElInput>
          <ElButton :icon="Refresh" @click="onTableRefresh" />
        </div>
      </div>
      <TableWithPagination
        size="small"
        :data="firewalls"
        :paginationTotal="firewalls.length"
        paginationLayout="total, prev, pager, next"
        @selectionChange="onTableSelectionChange"
      >
        <ElTableColumn type="selection" width="55" :selectable="isFirewallSelectable"/>
        <ElTableColumn property="firewallName" :label="t('firewallName')" />
        <ElTableColumn :label="t('firewallEdition')" >
          <template #default="scope">{{ t(`firewallEditions.${scope.row.firewallEdition}`) }}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('quotaState')" >
          <template #default="scope">{{ t(`quotaStates.${scope.row.firewallState}`) }}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('vpc')" >
          <template #default="scope">
            <div class="vpc">
              <div class="id">{{scope.row.vpcId}}</div>
              <div class="ip">{{scope.row.vpcIp}}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('defenseIpCountStats')" width="180px" >
          <template #default="scope">
            {{scope.row.protectionIpNum + OrderHelper.MIN_IP_COUNT}}/{{scope.row.ipProtectCount}}{{t('quantifierOfIp')}}
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('internetFlowProcessingCapacity')" >
          <template #default="scope">
            {{scope.row.flowProcessingCapacity + OrderHelper.MIN_FLOW_CAPACITY}}{{t('mbps')}}
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('orderedAt')" >
          <template #default="scope">
            {{scope.row.orderTime ? dayjs(scope.row.orderTime).format(t('dateFormat')) : '-'}}
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('expireAt')" >
          <template #default="scope">
            {{scope.row.expireTime ? dayjs(scope.row.expireTime).format(t('dateFormat')) : '-'}}
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('operations')" >
          <template #default="scope">
            <ElLink
              v-if="[Enums.FirewallState.Normal, Enums.FirewallState.Overdue].includes(scope.row.firewallState)"
              @click="onClickRenew(scope.row)"
            >
              {{t('quotaRenew')}}
            </ElLink>
            <ElLink
              v-if="[Enums.FirewallState.Normal].includes(scope.row.firewallState)"
              @click="onClickChange(scope.row)"
            >
              {{t('quotaChange')}}
            </ElLink>
            <ElLink
              v-if="[Enums.FirewallState.Normal].includes(scope.row.firewallState)"
              @click="onClickCancel(scope.row)"
            >
              {{t('quotaCancel')}}
            </ElLink>
          </template>
        </ElTableColumn>
      </TableWithPagination>
    </ElCard>
  </SubViewContainer>
</template>

<i18n lang="yaml" locale="zh-CN">
  toPurchase: '购买云防火墙（原生版）'
  batchRenew: '批量续订'
  quotaState: '配额状态'
  dateFormat: 'YYYY-MM-DD'
  quotaStates:
    all: '全部'
    normal: '正常'
    overdue: '已过期'
    unsubscribe: '已退订'
  searchType:
    firewallName: '云防火墙名称'
    vpcName: 'VPC 名称'
  inputToSearchPlease: 请输入搜索条件
  firewallName: '云防火墙名称'
  firewallEdition: '配额规格'
  firewallEditions:
    AdvancedEdition: '高级版'
  vpc: '虚拟私有云'
  defenseIpCountStats: '可防护/已防护公网 IP 数'
  quantifierOfIp: '个'
  internetFlowProcessingCapacity: '公网流量处理能力'
  mbps: 'Mbps'
  orderedAt: '配额订购时间'
  expireAt: '配额到期时间'
  operations: '操作'
  quotaRenew: '续订'
  quotaChange: '变配'
  quotaCancel: '退订'
  noProductCheckedMessage: '请先选择要续订的产品'
</i18n>

<style lang="scss" scoped>
.guide-steps {
  margin-bottom: 16px;
}

.table-controller,
.filters,
.quota-state {
  display: flex;
  flex-direction: row;
}

.table-controller {
  justify-content: space-between;
  font-size: 14px;
}

.filters {
  margin-bottom: 20px;

  .quota-state {
    align-items: center;
    margin-right: 10px;

    .label {
      margin-right: 10px;
      white-space: nowrap;
    }

    .el-select {
      width: 95px;
    }
  }

  .search-input {
    width: 440px;
    margin-right: 10px;

    :deep(.el-input__inner) {
      line-height: var(--el-input-height);
    }

    .el-select {
      width: 135px;
    }
  }
}

.table-with-pagination {
  .vpc {
    .id {
      color: var(--el-color-primary);
    }
  }

  .el-link {
    margin: 0 3px;
    font-size: 12px;
    color: var(--el-color-primary);
  }
}
</style>
